package sort;

public class MergeSort {
    private void merge(int[] arr ,int left, int mid, int right){
        int[] temp_arr = new int[right-left+1];
        int i=left;
        int j=mid+1;
        int k=0;
        while(i<=mid && j<=right){
            if(arr[i] >= arr[j]){
                temp_arr[k] = arr[j];
                j++;
            } else {
                temp_arr[k] = arr[i];
                i++;
            }
            k++;
        }

        while(i<=mid){
            temp_arr[k] = arr[i];
            k++;
            i++;
        }
        while(j<=right){
            temp_arr[k] = arr[j];
            j++;
            k++;
        }

        for(i=left; i<=right; i++){
            arr[i] = temp_arr[i-left];
        }
    }

    public void mergeSort(int[] arr, int left, int right){
        if(right > left){
            int mid = (left + right) /2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid+1, right);
            merge(arr, left, mid, right);
        }
    }

    public static void main(String[] args){
        MergeSort sort = new MergeSort();
        int[] arr = {5, 4, 3, 2, 1};
        sort.mergeSort(arr, 0, arr.length-1);
        for (int j : arr) {
            System.out.print(j);
        }
    }
}
